/* Copyright (C) 2008, 2009, 2010 Faindu GmbH, Switzerland.
* All Rights Reserved. The following is Source Code and is subject to all restrictions 
* on such code as contained in the license accompanying this project. */
package blocstac.editimage.scale
{
import blocstac.editimage.base.ImageModel;
import blocstac.editimage.base.ImageOperation;
import blocstac.util.Print;

import flash.geom.Point;

public class ScaleOperation implements ImageOperation
{
	private var _mouseLocationInUnscaledImageComp:Point
	private var _scaleInit:ScaleInit
	private var _keepRatio:Boolean
	
	function ScaleOperation(scaleInit:ScaleInit, mouseLocationInUnscaledImageComp:Point, keepRatio:Boolean)
	{
		_mouseLocationInUnscaledImageComp = mouseLocationInUnscaledImageComp
		_scaleInit = scaleInit
		_keepRatio = keepRatio
	}
	
	/** @inheritDoc */
	public function apply(state:ImageModel):void
	{
		var imageCorner:Point = _scaleInit.brImageCornerInRotationCompUnscaled
		var scaleX:Number = (_mouseLocationInUnscaledImageComp.x * _scaleInit.editedScaleX - _scaleInit.mouseToImageCornerOffsetUnscaled.x) / imageCorner.x
		var scaleY:Number = (_mouseLocationInUnscaledImageComp.y * _scaleInit.editedScaleY - _scaleInit.mouseToImageCornerOffsetUnscaled.y) / imageCorner.y
		
		if (scaleX < 0 || scaleY < 0) {
			return
		}
		
		if (_keepRatio) {
			var ratioX:Number = scaleX / _scaleInit.editedScaleX
			var ratioY:Number = scaleY / _scaleInit.editedScaleY
			if (ratioX < ratioY) {
				scaleY = _scaleInit.editedScaleY * ratioX
			} else {
				scaleX = _scaleInit.editedScaleX * ratioY
			}
		}
		
		state.editedScaleX = scaleX
		state.editedScaleY = scaleY
	}
		
	/** @inheritDoc */
	public function undo(state:ImageModel):void
	{
		state.editedScaleX = _scaleInit.editedScaleX
		state.editedScaleY = _scaleInit.editedScaleY
	}
	
}
}